package com.crhms.seabow.security;

import com.crhms.seabow.entity.Role;
import com.crhms.seabow.entity.User;
import com.crhms.seabow.entity.UserRole;
import com.crhms.seabow.service.RoleService;
import com.crhms.seabow.service.UserRoleService;
import com.crhms.seabow.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new ArrayList<>();

        User user = userService.getUserInfo(s);

        // 判断用户是否存在
        if(user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 添加权限
        List<UserRole> userRoles = userRoleService.getUserRoles(user.getId().toString());
        for (UserRole userRole : userRoles) {
            Role role = roleService.getRoles(userRole.getRoleId());
            authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
        }

        return new SecurityUser(user.getName(),user.getPassword(),authorities);
    }
}
